package com.qdxwx.manage.controller.my;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.bank.BankCardService;
import com.qdxwx.data.service.cash.CashApplyService;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.bank.BankCard;
import com.qdxwx.models.cash.CashApply;
import com.qdxwx.models.enums.*;
import com.qdxwx.models.manager.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 我的账户信息Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/my/account")
public class MyAccountController extends BaseController {
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountDetailService userAccountDetailService;
    @Autowired
    private BankCardService bankCardService;
    @Autowired
    private CashApplyService cashApplyService;

    /***
     * 我的账户
     */
    @GetMapping("/info.html")
    public String info(ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) {
            System.out.println("manager:null");
            return error404;
        }
        UserAccount userAccount = userAccountService.getByUserId(manager.getUserId());
        if (userAccount == null) {
            System.out.println("userAccount:null");
            return error404;
        }
        mmap.put("manager", manager);
        mmap.put("userAccount", userAccount);
        return "my/my-account-info";
    }

    /***
     * 查询账户记录
     */
    @GetMapping("/detail.html")
    public String detail() {
        return "my/my-account-detail";
    }

    /**
     * 查询账户信息列表
     */
    @PostMapping("/detail.json")
    @ResponseBody
    public TableDataInfo detailList(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager.getUserId() < 1) {
            return TableDataInfo.error("用户账户错误！");
        }
        UserAccountDetail accountHistory = new UserAccountDetail();
        accountHistory.setUserId(manager.getUserId());
        accountHistory.setActHistoryType(request.getParameter("actHistoryType"));
        accountHistory.setBizType(request.getParameter("bizType"));
        List<UserAccountDetail> list = userAccountDetailService.getList(accountHistory, PageRequest.form(request));
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(userAccountDetailService.count(accountHistory));
        return rspData;
    }

    @GetMapping("/take.html")
    public String take(ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null || manager.getUserId() < 1) return error500;
        UserAccount userAccount = userAccountService.getByUserId(manager.getUserId());
        if (userAccount == null) return error500;
        BankCard bankCard = new BankCard();
        bankCard.setInfoId(manager.getUserId());
        bankCard.setType(BankCardType.TEACHER.toString());
        List<BankCard> bankCardList = bankCardService.getList(bankCard, new PageRequest(1, 3));
        mmap.put("userAccount", userAccount);
        mmap.put("bankCardList", bankCardList);
        return "my/my-account-take";
    }

    /**
     * 查看卡号
     */
    @RequestMapping("/bank.json")
    @ResponseBody
    public AjaxResult getBank(HttpServletRequest request) {
        long id = TKConvert.toLong(request.getParameter("id"));
        if (id < 1) return error("选择错误");
        BankCard bankCard = bankCardService.get(id);
        if (bankCard == null) return error("选择错误");
        return AjaxResult.success(bankCard);
    }

    /**
     * 提现
     */
    @RequestMapping("/take.json")
    @ResponseBody
    public AjaxResult take(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error("登录超时");
        /*提取金额*/
        int drawMoney = Double.valueOf(TKConvert.toDouble(request.getParameter("drawMoney")) * 100).intValue();
        if (drawMoney < 10000 || (drawMoney % 10000 > 0)) return error("提现金额必须是100的倍数，最低提现100元");
        /*收款人*/
        String bankCardName = request.getParameter("bankCardName");
        if (TKString.isEmpty(bankCardName)) return error("请输入银行卡开户人");
        /*银行卡号*/
        String bankCardNumber = request.getParameter("bankCardNumber");
        if (TKString.isEmpty(bankCardNumber)) return error("请输入银行卡号");
        /*转账银行*/
        String bankName = request.getParameter("bankName");
        if (TKString.isEmpty(bankName)) return error("请输入开户银行");
        UserAccount userAccount = userAccountService.getByUserId(manager.getUserId());
        if (userAccount == null) return error("账户异常，找不到指定账户");
        if (userAccount.getAccountStatus().equals(AccountStatus.FROZEN.toString())) return error("账户被冻结，请联系管理员");
        if (userAccount.getBackAmount() < drawMoney) {
            return error("可提现金额不足");
        }
        /*冻结提现金额*/
        userAccount.setFrozenAmount(userAccount.getFrozenAmount() + drawMoney);
        /*余额减掉要提取的金额*/
        userAccount.setBalance(userAccount.getBalance() - drawMoney);
        /*返现余额减掉要提取的金额*/
        userAccount.setBackAmount(userAccount.getBackAmount() - drawMoney);
        userAccount.setVersion(userAccount.getVersion() + 1);
        /*更新账户信息*/
        int row = userAccountService.update(userAccount);
        if (row > 0) {
            /*创建提现交易记录*/
            UserAccountDetail userAccountDetail = new UserAccountDetail();
            userAccountDetail.setUserId(manager.getUserId());
            userAccountDetail.setActHistoryType(AccountHistoryType.DRAWMONEY.toString());
            userAccountDetail.setBalance(userAccount.getBalance());
            userAccountDetail.setBackAmount(userAccount.getBackAmount());
            userAccountDetail.setOrderAmount(drawMoney);
            userAccountDetail.setDescription("提现金额" + (drawMoney / 100) + "元");
            userAccountDetail.setBizType(AccountBizType.DRAWMONEY.toString());
            userAccountDetail.setVmAmount(userAccount.getVmAmount());
            userAccountDetail.setVersion(userAccount.getVersion());
            userAccountDetailService.insert(userAccountDetail);
            /*创建申请提现记录*/
            CashApply cashApply = new CashApply();
            cashApply.setInfoId((int) manager.getUserId());
            cashApply.setInfoName(manager.getManagerName());
            cashApply.setType(BankCardType.TEACHER.toString());
            cashApply.setAmount(drawMoney);
            cashApply.setBankCardNumber(bankCardNumber);
            cashApply.setBankName(bankName);
            cashApply.setBankCardName(bankCardName);
            cashApply.setStatus(CashApplyStatus.NOTAPPROVED.getValue());
            cashApply.setDescription("提现金额" + (drawMoney / 100) + "元");
            cashApplyService.insert(cashApply);
            /*创建历史提现卡号*/
            BankCard bankCard = new BankCard();
            bankCard.setInfoId(manager.getUserId());
            bankCard.setType(BankCardType.TEACHER.toString());
            bankCard.setBankCardNumber(bankCardNumber);
            int count = bankCardService.count(bankCard);
            if (count < 1) {
                bankCard.setBankName(bankName);
                bankCard.setBankCardName(bankCardName);
                bankCardService.insert(bankCard);
            }
            return success();
        } else {
            return error("提成操作失败，请稍后再试");
        }
    }

}
